package net.raebiger.spreadsheetcat.preference;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import net.raebiger.spreadsheetcat.R;
import net.raebiger.spreadsheetcat.model.WorksheetDetails;
import net.raebiger.spreadsheetcat.spreadsheet.RetrieveFeedTask;
import net.raebiger.spreadsheetcat.spreadsheet.RetrieveWorkbookDetails;
import net.raebiger.spreadsheetcat.util.DialogUtil;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.ListPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;

import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;

public class SpreadsheetPreferences {
	private final PreferenceActivity context;

	protected static final String PREF_SPREADSHEET = "prefSpreadsheet";

	public static final String PREF_WORKSHEETDETAILS = "prefWorksheetDetails";

	private final AccountPreferences accountPreferences;

	private ListPreference spreadSheetPref;
	private Map<String, String> spreadsheetKeyMap;

	private static SharedPreferences sharedPreference;

	@SuppressWarnings("deprecation")
	protected SpreadsheetPreferences(PreferenceActivity context, AccountPreferences accountPreferences) {
		this.context = context;
		this.accountPreferences = accountPreferences;

		spreadSheetPref = (ListPreference) context.findPreference(PREF_SPREADSHEET);

	}

	protected void enablePref(String authToken) {
		spreadSheetPref.setEnabled(true);
		spreadSheetPref.setSelectable(true);
		updatePrefSpeadsheetSummary(authToken);
	}

	protected void disablePref() {
		spreadSheetPref.setEnabled(false);
		spreadSheetPref.setSelectable(false);
		spreadSheetPref.setSummary(R.string.pref_spreadsheet_summaryDisabled);
	}

	private Map<String, String> populateSpreadsheetPref(final ListPreference spreadSheetPref, SpreadsheetFeed feed) {
		List<SpreadsheetEntry> spreadsheets = feed.getEntries();
		String[] sheetNames = new String[spreadsheets.size()];
		String[] sheetKeys = new String[spreadsheets.size()];
		Map<String, String> spreadsheetKeyMap = new Hashtable<String, String>();
		int i = 0;
		for (SpreadsheetEntry entry : spreadsheets) {
			Log.i("SSC", "entry: " + entry.getTitle().getPlainText());
			sheetNames[i] = entry.getTitle().getPlainText();
			sheetKeys[i] = entry.getKey();
			spreadsheetKeyMap.put(entry.getKey(), entry.getTitle().getPlainText());
			++i;
		}
		spreadSheetPref.setEntries(sheetNames);
		spreadSheetPref.setEntryValues(sheetKeys);
		return spreadsheetKeyMap;
	}

	private String getStoredSpreadsheetIdOrNull() {
		SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
		String storedSpreadsheet = sharedPrefs.getString(PREF_SPREADSHEET, null);
		return storedSpreadsheet;
	}

	protected void updatePrefSpeadsheetSummary(String authToken) {
		if (spreadsheetKeyMap == null) {
			if (readSpreadsheetMap(authToken) == null) {
				Log.e("SSC", "Cannot update summary for spreadsheet user prefs: No mapping given.");
				DialogUtil.getInstance().showDialog(R.string.error_msg_cannotReadSpreadsheets, context);
				return;
			}
		}
		String spreadsheetIdOrNull = getStoredSpreadsheetIdOrNull();
		if (spreadsheetIdOrNull != null) {
			String spreadsheetName = spreadsheetKeyMap.get(spreadsheetIdOrNull);
			if (spreadsheetName == null) {
				spreadsheetName = spreadsheetIdOrNull;
			}
			spreadSheetPref.setSummary(String.format(context.getString(R.string.pref_spreadsheet_summary),
					spreadsheetName));

		} else {
			spreadSheetPref.setSummary(R.string.pref_spreadsheet_summaryNoneSelected);
		}
		updateSpreadsheetDetails(spreadsheetIdOrNull, authToken);
	}

	private void updateSpreadsheetDetails(String spreadsheetIdOrNull, String authToken) {
		if (spreadsheetIdOrNull == null) {
			// TODO clear details
		} else {
			RetrieveWorkbookDetails task = new RetrieveWorkbookDetails(authToken, spreadsheetIdOrNull);
			task.execute(new Void[] {});
			try {
				WorksheetDetails worksheetDetails = task.get();
				if (worksheetDetails != null) {
					if (sharedPreference == null) {
						sharedPreference = PreferenceManager.getDefaultSharedPreferences(context);
					}
					Editor sharedPrefEditor = sharedPreference.edit();
					sharedPrefEditor.putString(PREF_WORKSHEETDETAILS, worksheetDetails.toString());
					sharedPrefEditor.commit();
				} else {
					Log.e("SSC", "Could not read worksheet details.");
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private Map<String, String> readSpreadsheetMap(String authToken) {

		// Define the URL to request. This should never change.
		RetrieveFeedTask task = new RetrieveFeedTask(authToken);
		task.execute(new Void[] {});
		SpreadsheetFeed feed = null;
		try {
			feed = task.get();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (feed != null) {
			spreadsheetKeyMap = populateSpreadsheetPref(spreadSheetPref, feed);
		} else {
			Exception exception = task.getException();
			if (exception == null) {
				// *sigh* what now?
				Log.e("SSC", "Failed to retrieve spreadsheet feed. No exception, though.");
				return null;
			} else {
				Log.e("SSC", "Failed to retrieve spreadsheet feed. Exception follows. ", exception.getCause());
				return null;
			}
		}
		return spreadsheetKeyMap;
	}

	protected void readSelectedSpreadsheet(String authToken) {
		String storedSpreadsheetIdOrNull = getStoredSpreadsheetIdOrNull();
		if (storedSpreadsheetIdOrNull == null) {
			return;
		}
		RetrieveWorkbookDetails task = new RetrieveWorkbookDetails(authToken, storedSpreadsheetIdOrNull);
		task.execute(new Void[] {});
	}
}
